<template>
  <div class="home">
    <div class="time">
      <h2>当前时间: {{ currentTime }}</h2>
    </div>
    <div class="weather">
      <h3>温度: {{ weather ? weather.temperature : '加载中...' }} 摄氏度</h3>
      <p v-if="weather">
        <strong>天气状况:</strong> {{ weather.weather }}
      </p>
      <p v-if="weather">
        <strong>风速:</strong> {{ weather.windpower }} km/h
      </p>
      <p v-if="weather">
        <strong>空气湿度:</strong> {{ weather.humidity }}
      </p>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      currentTime: '', // 用于存储当前时间
      weather: null,    // 用于存储天气数据
      apiKey: 'a5ab1269b672f84833566aa2d47760ad', // 替换成你的高德 API Key
      city: '370613' // 默认城市
    };
  },
  created() {
    this.getWeather();
    this.updateTime();
  },
  methods: {
    // 获取天气信息
    async getWeather() {
      try {
        const response = await axios.get(`https://restapi.amap.com/v3/weather/weatherInfo`, {
          params: {
            key: this.apiKey,
            city: this.city, // 获取指定城市的天气
            extensions: 'base', // 基本信息
          }
        });

        if (response.data.status === '1' && response.data.lives.length > 0) {
          const data = response.data.lives[0];
          this.weather = {
            temperature: data.temperature,
            weather: data.weather,
            humidity :data.humidity,
            windpower:data.windpower
          };
        }
      } catch (error) {
        console.error('天气获取失败', error);
      }
    },

    // 更新当前时间
    updateTime() {
      setInterval(() => {
        const now = new Date();
        this.currentTime = now.toLocaleTimeString();
      }, 1000); // 每秒更新一次时间
    }
  }
};
</script>

<style scoped>
.home {
  text-align: center;
  margin-top: 20px;
}

.time {
  font-size: 24px;
}

.weather {
  margin-top: 20px;
  font-size: 18px;
}

.weather strong {
  font-weight: bold;
}
</style>
